package cn.itcast.robot;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.itcast.AppConfig;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import cn.itcast.utils.HttpUtil;

//import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private EditText et_account;   //账号输入框
    private EditText et_password;  //密码输入框
    private Button btn_login;      //登录按钮
    private Button btn_register;      //登录按钮
    private boolean flag_login=false;      //登录按钮
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //通过工具类FileSaveQQ中的getUserInfo()方法获取QQ账号和密码信息
        Map<String, String> userInfo = FileSaveQQ.getUserInfo(this);
        //Map<String, String> userInfo = SP_SAVE.getUserInfo(this);
        if (userInfo != null) {
            et_account.setText(userInfo.get("account"));   //将获取的账号显示到界面上
            et_password.setText(userInfo.get("password")); //将获取的密码显示到界面上
        }
    }

    private void initView() {
        et_account = (EditText) findViewById(R.id.et_account);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_register = (Button) findViewById(R.id.btn_register);
        //设置按钮的点击监听事件
        btn_login.setOnClickListener((View.OnClickListener) this);
        btn_register.setOnClickListener((View.OnClickListener) this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                //当点击登录按钮时，获取界面上输入的QQ账号和密码
                String account = et_account.getText().toString().trim();
                String password = et_password.getText().toString();
                //检验输入的账号和密码是否为空
                if (TextUtils.isEmpty(account)) {
                    Toast.makeText(this, "请输入QQ账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
//                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                //保存用户信息
                boolean isSaveSuccess = FileSaveQQ.saveUserInfo(this, account,
                        password);


                String url = AppConfig.host + "/app/user/api/login";
                Map<String,String> param = new HashMap<>();
                param.put("userName", account);
                param.put("password", password);

                Log.d("code", ""+url+param.toString());

                HttpUtil.post(url, param, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "服务器通信失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);

                                    Log.d("code", ""+jsonObject.getString("code"));
                                    if (jsonObject.getString("code").equals("200")) {
                                        flag_login=true;

//                                        if(flag_login==true){
                                            flag_login=false;
                                            Intent intent = new Intent(MainActivity.this, RobotActivity.class);
                                            startActivityForResult(intent, 1);
//                                        }
//                                        editor.putBoolean( "autologin",false);
//                                        editor.putInt("userId",jsonObject.getInt("userId"));
//                                        editor.putInt("classesId",jsonObject.getInt("classesId"));
//                                        editor.putString("userName",jsonObject.getString("userName"));
//                                        editor.putString("nickName",jsonObject.getString("nickName"));
//                                        editor.apply();
                                        Toast.makeText(MainActivity.this, jsonObject.getString("nickName")+" 登录成功", Toast.LENGTH_SHORT).show();
//                                        if (autoLogoin.isChecked())
//                                        {
//                                            editor.putBoolean( "autologin",true);
//                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
//                                            Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
//                                            cal.add(Calendar.DAY_OF_MONTH, +7);//取当前日期的后7天.
//                                            editor.putString("failure_time",df.format(cal.getTime()));
//                                            editor.apply();
//                                        }
//                                        showMain();
                                    }
                                    else
                                    {
                                        Toast.makeText(MainActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });

//                if(flag_login==true){
//                    flag_login=false;
//                    Intent intent = new Intent(MainActivity.this, RobotActivity.class);
//                    startActivityForResult(intent, 1);
//                }

                /*  boolean isSaveSuccess = SPSaveQQ.saveUserInfo(this, account, password);*/
//                if (isSaveSuccess) {
//                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
//                } else {
//                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
//                }



                break;
            case R.id.btn_register:
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
//                intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivityForResult(intent, 1);


                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onKeyDown", "onActivityResult");
        Log.d("onKeyDown", "requestCode:"+requestCode+"    resultCode:"+resultCode);

        if (requestCode==1&&resultCode==2){
            Log.d("onKeyDown", "onActivityResult");
            MainActivity.this.finish();
            System.exit(0);
        }
    }
}